package game.game.network.client;

import game.engine.network.client.IControllerClient;
import game.engine.network.cmd.Command;
import game.engine.network.cmd.EnumCommand;
import game.game.network.cmd.CmdSReturnCacheMap;
import game.game.network.cmd.CmdSReturnContext;
import game.game.network.cmd.CmdSReturnPosition;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;

import json.JSONObject;

public class ListenerServerClient extends Thread
{
	private Socket _socket;

	private IControllerClient _controller;

	public ListenerServerClient(Socket pSocket, IControllerClient pController)
	{
		this._socket = pSocket;
		this._controller = pController;
	}

	public void run()
	{
		try
		{
			BufferedReader ois = new BufferedReader( new InputStreamReader( _socket.getInputStream() ) );
			String cmd = null;
			while ( (cmd = ois.readLine()) != null )
			{
				System.out.println(cmd);
				JSONObject jSONObject = new JSONObject( cmd );
				int objId = jSONObject.getInt( Command.KEY_IDCMD );
				System.out.println(objId);
				if ( objId == EnumCommand.CMD_SERV_RETURN_CACHE_MAP.getValue() )
				{
					new CmdSReturnCacheMap( jSONObject ).execute( _controller );
				}
				if ( objId == EnumCommand.CMD_SERV_RETURN_CONTEXT.getValue() )
				{
					new CmdSReturnContext( jSONObject ).execute( _controller );
				}
				if ( objId == EnumCommand.CMD_SERV_RETURN_POSITION.getValue() )
				{
					new CmdSReturnPosition( jSONObject ).execute( _controller );
				}

			}
			ois.close();
		}
		catch ( Exception e )
		{
			e.printStackTrace();
		}
	}
}
